package com.radiation.rms.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.radiation.rms.common.R;
import com.radiation.rms.common.RMSCommon;
import com.radiation.rms.common.RMSConstant;
import com.radiation.rms.entity.AclUserDepartment;
import com.radiation.rms.entity.Area;
import com.radiation.rms.entity.User;
import com.radiation.rms.mapper.UserMapper;
import com.radiation.rms.service.AclUserDepartmentService;
import com.radiation.rms.service.AreaService;
import com.radiation.rms.service.UserService;
import com.radiation.rms.utils.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-01-12
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AclUserDepartmentService aclUserDepartmentService;

    @Autowired
    private RMSCommon rmsCommon;

    @Autowired
    private AreaService areaService;

    @Override
    public User selectByUsername(String username) {
        return baseMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public R index(Long page, Long limit, User userQueryVo) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        List<String> userIds = rmsCommon.getUserIds(username);
        User user = selectByUsername(username);
        List<String> departmentIds = rmsCommon.getUserByUserId(user.getId());
        if (!username.equals(RMSConstant.ADMIN)) {
            List<String> list = areaService.getHospitalId(departmentIds);
            int total = 0;
            for (String s : list) {
                QueryWrapper<Area> wrapper = new QueryWrapper<>();
                wrapper.eq("father_id", s);
                int count = areaService.count(wrapper);
                total = total + count;
            }
            if (total != departmentIds.size()) {
                return R.error().message(RMSConstant.ALLOCATION_ERROR);
            }
            userIds = userIds.stream().filter(s -> {
                List<String> userByUserId = rmsCommon.getUserByUserId(s);
                return userByUserId.size() < departmentIds.size();
            }).collect(Collectors.toList());
        }
        if (userIds.size() == 0) {
            userIds.add(user.getId());
        }
        Page<User> pageParam = new Page<>(page, limit);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(userQueryVo.getUsername())) {
            wrapper.like("username", userQueryVo.getUsername());
        }
        wrapper.in("id", userIds);
        IPage<User> pageModel = page(pageParam, wrapper);
        log.info(pageModel.getRecords().toString());
        return R.ok().data("items", pageModel.getRecords()).data("total", pageModel.getTotal());
    }

    @Override
    public R toAsdata(String userId) {
        List<String> departmentId = getDepartmentId(userId);
        return R.ok().data("items", departmentId);
    }

    private List<String> getDepartmentId(String userId) {
        QueryWrapper<AclUserDepartment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<AclUserDepartment> departments = aclUserDepartmentService.list(queryWrapper);
        return departments.stream().map(AclUserDepartment::getDepartmentId).collect(Collectors.toList());
    }

    @Override
    public R doAsdata(String userId, String[] departmentIds) {
        
        if (departmentIds.length != 1) {
            List<String> hospitalId = areaService.getHospitalId(Arrays.asList(departmentIds));
            int total = 0;
            for (String s : hospitalId) {
                QueryWrapper<Area> wrapper = new QueryWrapper<>();
                wrapper.eq("father_id", s);
                int count = areaService.count(wrapper);
                total = total + count;
            }
            if (total != departmentIds.length) {
                return R.error().message(RMSConstant.ALLOCATION_ERROR);
            }
        }
        List<AclUserDepartment> userDepartments = new ArrayList<>();
        aclUserDepartmentService.remove(new QueryWrapper<AclUserDepartment>().eq("user_id", userId));
        for (String departmentId : departmentIds) {
            if (StringUtils.isEmpty(departmentIds)) {
                continue;
            }
            AclUserDepartment userDepartment = new AclUserDepartment();
            userDepartment.setUserId(userId);
            userDepartment.setDepartmentId(departmentId);

            userDepartments.add(userDepartment);
        }
        aclUserDepartmentService.saveBatch(userDepartments);
        return R.ok();
    }

    @Override
    public R changePassword(User user) {
        user.setPassword(MD5.encrypt(user.getPassword()));
        baseMapper.updateById(user);
        return R.ok();
    }
}
